package cn.stylefeng.guns.modular.biz.timer;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.stylefeng.guns.modular.biz.entity.LabMainInfoRlm;
import cn.stylefeng.guns.modular.biz.pojo.request.LabMainInfoRlmRequest;
import cn.stylefeng.guns.modular.biz.pojo.response.LabMainInfoRlmVo;
import cn.stylefeng.guns.modular.biz.service.LabMainInfoRlmService;
import cn.stylefeng.roses.kernel.timer.api.TimerAction;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Component
public class GetMesLabMainInfoRlmTimer implements TimerAction {

    @Resource
    private LabMainInfoRlmService labMainInfoRlmService;

    /**
     *
     * @param params 是URL地址："http://localhost:18080/LabMainInfo/getLabMainInfoQM00020ByDate";
     */
    @Override
    public void action(String params) {
        RestTemplate restTemplate = new RestTemplate();

        System.out.println("定时任务执行了,地址URL："+params);
        JSONObject requestBody = new JSONObject();

        // 设置请求体中的current_date字段为当前日期
//        requestBody.set("current_date",DateUtil.today());
        requestBody.set("current_date","2024-08-19");
        // 发送POST请求，获取响应
        ResponseEntity<Object> response = restTemplate.postForEntity(params, requestBody, Object.class);
        // 判断响应状态码是否为2xx成功
        if (response.getStatusCode().is2xxSuccessful()) {
            // 处理成功响应
            System.out.println("请求成功");
            // 获取响应体
            Object responseBody = response.getBody();
            // 将响应体转换为LabMainInfoVo类型的列表
           List<LabMainInfoRlmVo> list= JSONUtil.parseArray(responseBody).toList(LabMainInfoRlmVo.class);
            // 遍历列表
            for (LabMainInfoRlmVo labMainInfoRlmVo : list) {
                // 根据sample_id查询LabMainInfo
                LabMainInfoRlm IsLabMainInfo=labMainInfoRlmService.getOne(new QueryWrapper<LabMainInfoRlm>().eq("sample_id",labMainInfoRlmVo.getSampleId()));
              // 如果查询结果为空
              if(ObjectUtil.isEmpty(IsLabMainInfo)){
                  // 创建LabMainInfoRlmRequest对象
                  LabMainInfoRlmRequest labMainInfoRlmRequest=new LabMainInfoRlmRequest();
                  // 将labMainInfoVo对象中的属性值复制到LabMainInfoRlmRequest对象中
                  BeanUtils.copyProperties(labMainInfoRlmVo,labMainInfoRlmRequest);
                  // 添加LabMainInfoRlmRequest对象到数据库
                  labMainInfoRlmService.add(labMainInfoRlmRequest);
              }
            }
        } else {
            // 处理失败响应
        }
    }


}
